import type { RouteRecordStringComponent } from '@vben/types';

import { requestClient } from '#/api/request';
import { handleTree } from '#/utils/tree';

/**
 * 后端菜单数据项接口
 * 注意：requestClient 配置了 responseReturn: 'data'，所以直接返回 data 字段的内容
 */
interface BackendMenuItem {
  id: number;
  pid: number;
  path: string;
  component: string;
  name: string;
  meta: {
    hideInMenu: number;
    icon: string;
    keepAlive: number;
    link: string;
    menuVisibleWithForbidden: number;
    order: number;
    title: string;
  };
}

/**
 * 获取用户所有菜单
 * 自动将后端数据转换为前端路由格式
 */
export async function getAllMenusApi(): Promise<RouteRecordStringComponent[]> {
  try {
    // requestClient 会自动提取 data 字段，所以这里直接获取菜单数组
    const menuData =
      await requestClient.get<BackendMenuItem[]>('/user/menu/list');

    // 转换为前端路由格式
    const routes = convertBackendMenuToRoutes(menuData);

    return routes;
  } catch (error) {
    console.error('获取菜单数据失败:', error);
    return [];
  }
}

/**
 * 将后端菜单数据转换为前端路由格式
 * @param menuData 后端返回的菜单数据数组
 * @returns 转换后的路由配置数组
 */
function convertBackendMenuToRoutes(
  menuData: BackendMenuItem[],
): RouteRecordStringComponent[] {
  if (!Array.isArray(menuData) || menuData.length === 0) {
    console.warn('Invalid menu data:', menuData);
    return [];
  }

  // 使用 handleTree 构建树形结构
  const treeData = handleTree(menuData, 'id', 'pid', 'children');

  // 递归转换树形数据为路由格式
  return convertTreeToRoutes(treeData);
}

/**
 * 递归转换树形数据为路由格式
 * @param treeData 树形菜单数据
 * @returns 路由配置数组
 */
function convertTreeToRoutes(treeData: any[]): RouteRecordStringComponent[] {
  return treeData.map((item) => {
    const route: RouteRecordStringComponent = {
      path: item.path,
      name: item.name,
      component: item.component,
      meta: {
        title: item.meta.title,
        order: item.meta.order,
        icon: item.meta.icon,
        hideInMenu: item.meta.hideInMenu === 1,
        keepAlive: item.meta.keepAlive === 1,
        link: item.meta.link || undefined,
        menuVisibleWithForbidden: item.meta.menuVisibleWithForbidden === 1,
      },
    };

    // 如果有子菜单，递归处理
    if (item.children && item.children.length > 0) {
      route.children = convertTreeToRoutes(item.children);
    }

    return route;
  });
}
